package logic

import (
	"context"
	"encoding/xml"
	"fmt"
	"laundry-service/entity"
	"time"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type WkStNtfCallbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

type SFReply struct {
	XMLName xml.Name `xml:"Response"`
	Head    string   `xml:"head"`
	Msg     string   `xml:"msg"`
}

func NewWkStNtfCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WkStNtfCallbackLogic {
	return &WkStNtfCallbackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WkStNtfCallbackLogic) processNtf(obj *entity.WkStNtfReq) error {
	o, err := l.svcCtx.Db.GetOrderBySFBillCode(obj.WbillNo)
	if err != nil {
		return fmt.Errorf("get order code from db error: '%v'; %v", obj, err)
	}

	log := new(entity.BagLog)
	log.OrderId = o.ID
	log.CreatedAt = time.Now()

	switch obj.Status {
	case "DQR":
		log.State = 5
		log.Remark = "已预检待确认"
		break
	case "DYJ":
		log.State = 5
		log.Remark = "已入厂待预检"
		break
	case "XDZ":
		log.State = 6
		log.Remark = "工厂洗护中"
		break
	case "ZJZ":
		log.State = 7
		log.Remark = "工厂质检中"
		break
	case "XDWB_DHJ":
		log.State = 8
		log.Remark = "洗涤完毕待回寄"
		break
	case "XDWB":
		log.State = 8
		log.Remark = "回寄运输中"
		break
	case "FWWB":
		log.State = 10
		log.Remark = "服务完毕"
		break
	}
	return l.svcCtx.Db.SaveBagLog(log)
}

func (l *WkStNtfCallbackLogic) finishProcess(businessErr error) (resp []byte, err error) {
	if businessErr != nil {
		logx.Error(businessErr)
	}
	bin, _ := xml.MarshalIndent(&SFReply{Head: "OK"}, "", "  ")
	return bin, nil
}

func (l *WkStNtfCallbackLogic) WkStNtfCallback(req *types.WkStNtfReq) (resp []byte, err error) {
	var obj = entity.WkStNtfReq{}
	err = xml.Unmarshal([]byte(req.Pkg), &obj)
	if err != nil {
		return l.finishProcess(err)
	}
	return l.finishProcess(l.processNtf(&obj))
}
